﻿// The MIT License (MIT)
// Copyright (c) 2014 LuoZhihui
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the “Software”), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System.Collections.Generic;
using System.Threading;

namespace EasyTelnet
{
    /// <summary>
    ///     Telnet 脚本会话
    /// </summary>
    public class TelnetScriptSession : TelnetSessionBase
    {
        private readonly ManualResetEventSlim _waitExitSignal = new ManualResetEventSlim(false);
        /// <summary>
        ///     交互脚本队列
        /// </summary>
        private readonly Queue<Script> _scriptQueue = new Queue<Script>();

        /// <summary>
        /// 创建Telnet脚本会话( 默认端口23 超时时间60秒)
        /// </summary>
        /// <param name="host"></param>
        /// <param name="credentials"></param>
        /// <param name="netVirtualTerminal"></param>
        public TelnetScriptSession(string host, Credentials credentials, NetVirtualTerminal netVirtualTerminal)
            : this(host, 23, credentials, netVirtualTerminal)
        {
            
        }

        /// <summary>
        /// 创建Telnet脚本会话( 超时时间60秒)
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="credentials"></param>
        /// <param name="netVirtualTerminal"></param>
        public TelnetScriptSession(string host, int port, Credentials credentials, NetVirtualTerminal netVirtualTerminal)
            : this(host, port, 60, 60, credentials, netVirtualTerminal)
        {
            
        }

        /// <summary>
        ///   创建Telnet脚本会话
        /// </summary>
        /// <param name="host">主机</param>
        /// <param name="port">端口</param>
        /// <param name="receiveTimeout">读取超时</param>
        /// <param name="sendTimeout">发送超时</param>
        /// <param name="credentials">登陆凭据</param>
        /// <param name="netVirtualTerminal">网络虚拟终端</param>
        public TelnetScriptSession(string host, int port, int receiveTimeout, int sendTimeout, Credentials credentials,NetVirtualTerminal netVirtualTerminal)
            : base(host, port, receiveTimeout, sendTimeout, credentials, netVirtualTerminal)
        {
        }

        /// <summary>
        ///    添加交互脚本，按 FIFO方式执行
        /// </summary>
        /// <param name="waitPrompt"></param>
        /// <param name="command"></param>
        /// <param name="caseSensitive"></param>
        /// <param name="errorMessage"></param>
        public TelnetSessionBase AddScript(string waitPrompt, string command, bool caseSensitive, string errorMessage)
        {
            _scriptQueue.Enqueue(new Script {WaitPrompt = waitPrompt, Command = command, CaseSensitive = caseSensitive, ErrorMessage = errorMessage});
            return this;
        }

        /// <summary>
        /// 启动会话
        /// </summary>
        public override void SessionStart()
        {
 	         base.SessionStart();
            _waitExitSignal.Wait();
        }
      
        /// <summary>
        ///     收到数据处理程序
        /// </summary>
        /// <param name="args"></param>
        protected override void SessionHook(DataAvailableEventArgments args)
        {
            if (!IsLogin) return;

            if (_scriptQueue.Count == 0)
            {
                var item = FindData(Credentials.CommandPrompt, false);
                if (string.IsNullOrEmpty(item)) return;
                SendLogout(false);
                _waitExitSignal.Set();
            }
            else
            {
                var script = _scriptQueue.Peek();
                var item = FindData(script.WaitPrompt, script.CaseSensitive);
                if (string.IsNullOrEmpty(item)) return;

                SendAsync(script.Command, true);
                _scriptQueue.Dequeue();
            }
        }

        /// <summary>
        ///     交互脚本
        /// </summary>
        public struct Script
        {
            /// <summary>
            ///     只有在服务器响应数据中出现这个符号，才可以执行交互对象约定的脚本
            /// </summary>
            public string WaitPrompt { get; set; }

            /// <summary>
            ///     交互指令
            /// </summary>
            public string Command { get; set; }

            /// <summary>
            ///     大小写敏感
            /// </summary>
            public bool CaseSensitive { get; set; }

            /// <summary>
            ///     为找到标志符号的提示信息。
            /// </summary>
            public string ErrorMessage { get; set; }
        }
    }
}